<?php

namespace app\services;

use plugin\admin\app\model\DesignerApplication;
use plugin\admin\app\model\UserCompany;
use plugin\admin\app\model\UserCompanyProduct;

class DesignerApplicationService
{
    public static function apply($data)
    {
        $userId = get_user_id();

        // Check the latest application status
        $latestApplication = DesignerApplication::where('user_id', $userId)
            ->orderByDesc('application_date')
            ->first();

        if ($latestApplication && $latestApplication->is_approved != DesignerApplication::STATUS_REJECTED) {
            throw new \Exception('当前状态无法提交新申请');
        }

        // Validate required fields
        if (empty($data['name']) || empty($data['phone_number'])  || empty($data['company_name'])  || empty($data['business_license'])  || empty($data['logo'])) {
            throw new \Exception('必填项缺失');
        }

        // Prepare application data
        $applicationData = [
            'name' => $data['name'],
            'phone_number' => $data['phone_number'],
            'email' => $data['email'],
            'logo' => $data['logo'],
            'business_license' => $data['business_license'],
            'company_name' => $data['company_name'] ?? null, // Optional field
            'is_approved' => DesignerApplication::STATUS_PENDING, // Default to pending
            'application_date' => date('Y-m-d H:i:s'),
            'user_id' => $userId,
        ];

        // Insert application
        DesignerApplication::insert($applicationData);
    }

    public static function getLatestApplicationStatus()
    {
        $userId = get_user_id();

        // Query the latest application by user_id and application_date
        $application = DesignerApplication::where('user_id', $userId)
            ->orderByDesc('application_date')
            ->first();

        if (!$application) {
            throw new \Exception('未找到申请记录');
        }

        return [
            'is_approved' => $application->is_approved,
            'approval_comment' => $application->approval_comment,
            'application_date' => $application->application_date,
        ];
    }

    public static function getDetail($userId)
    {
        // Query the latest application by user_id and application_date
        $application = UserCompany::where('user_id', $userId)
            ->first();

        if (!$application) {
            return [];
        }

        return [
            'logo' => $application->company_logo,
            'company_name' => $application->company_name,
            'count' => $application->count
        ];
    }
}